<?php

class Application_Model_ExplicitCatanMapper {

    protected $_dbTable;

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_ExplicitCatan');
        }
        return $this->_dbTable;
    }

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Ungueltige Gateway-Klasse fuer Tabellendaten');
        }
        $this->_dbTable = $dbTable;
    }

    public function save(Application_Model_ExplicitCatanModel $catan) {
        $data = array(
            'id' => $catan->getId(),
            'event_id' => $catan->getEvent_id(),
            'type_id' => $catan->getType_id(),
            'winner_id' => $catan->getWinner_id(),
        );
        if (null === $catan->getId()) {
            unset($data['id']);

            $catan->setId($this->getDbTable()->insert($data));
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $data['id']));
        }
        return $catan;
    }

    public function find($id, Application_Model_ExplicitCatanModel $catan) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return null;
        }
        $row = $result->current();
        $catan->setId($row['id'])
                ->setEvent_id($row['event_id'])
                ->setType_id($row['type_id'])
                ->setWinner_id($row['winner_id']);
        $gameTypeRow = $row->findParentRow('Application_Model_DbTable_ExplicitCatanType');
        $catan->setType($gameTypeRow->name);
        $winnerRow = $row->findParentRow('Application_Model_DbTable_User');
        $catan->setWinner($winnerRow->salutation);
        return $catan;
    }

    public function fetchAll($where = null, $order = null, $count = null, $offset = null) {
        $resultSet = $this->getDbTable()->fetchAll($where, $order, $count, $offset);
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_ExplicitCatanModel;
            $entry->setId($row['id'])
                    ->setEvent_id($row['event_id'])
                    ->setType_id($row['type_id'])
                    ->setWinner_id($row['winner_id']);
            $gameTypeRow = $row->findParentRow('Application_Model_DbTable_ExplicitCatanType');
            $entry->setType($gameTypeRow->name);
            $winnerRow = $row->findParentRow('Application_Model_DbTable_User');
            $entry->setWinner($winnerRow->salutation);
            $entries[] = $entry;
        }
        return $entries;
    }

    public function delete($catanId) {
        if ($catanId instanceof Application_Model_ExplicitCatanModel) {
            $catanId = $catanId->id;
        }
        return $this->getDbTable()->delete(array('id = ?' => $catanId));
    }

}

